package com.example.bookappgraduation.fragments;

// ... imports (类似 BookListActivity)
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.example.bookappgraduation.R;
import com.example.bookappgraduation.adapters.BookAdapter;
import com.example.bookappgraduation.models.Book;
import com.example.bookappgraduation.utils.VolleySingleton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends Fragment {

    private RecyclerView recyclerViewHomeBooks;
    private BookAdapter bookAdapter;
    private List<Book> bookList;
    private ProgressBar progressBar;
    private final String API_KEY = "b55327fd83f2024e30500e63448a565d";
    // 此处使用 "252" (通常是综合/新书)，可以换成从分类接口获取到的任何其他ID
    String defaultCatalogId = "252";
    public HomeFragment() { /* Required empty public constructor */ }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerViewHomeBooks = view.findViewById(R.id.recyclerViewHomeBooks);
        progressBar = view.findViewById(R.id.progressBarHome);
        recyclerViewHomeBooks.setLayoutManager(new LinearLayoutManager(getContext()));
        bookList = new ArrayList<>();
        bookAdapter = new BookAdapter(getContext(), bookList);
        recyclerViewHomeBooks.setAdapter(bookAdapter);

        fetchHomeBooks();

        return view;
    }

    private void fetchHomeBooks() {
        progressBar.setVisibility(View.VISIBLE);
        // 获取所有书籍（API分页的第一页）
        String url = "http://apis.juhe.cn/goodbook/query?key=" + API_KEY + "&catalog_id=" + defaultCatalogId +"&rn=30"; // rn=20, 显示20条

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                response -> {
                    progressBar.setVisibility(View.GONE);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt("error_code") == 0) {
                            JSONObject resultObject = jsonObject.getJSONObject("result");
                            JSONArray dataArray = resultObject.getJSONArray("data");
                            bookList.clear();
                            for (int i = 0; i < dataArray.length(); i++) {
                                JSONObject bookObject = dataArray.getJSONObject(i);
                                Book book = new Book(
                                        bookObject.optString("title"),
                                        bookObject.optString("sub1"),
                                        bookObject.optString("sub2"),
                                        bookObject.optString("img"),
                                        bookObject.optString("catalog"),
                                        bookObject.optString("reading"),
                                        bookObject.optString("online"),
                                        bookObject.optString("bytime")
                                );
                                bookList.add(book);
                            }
                            bookAdapter.notifyDataSetChanged();
                            if(bookList.isEmpty()){
                                Toast.makeText(getContext(), "暂时没有书籍推荐", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getContext(), "获取书籍失败: " + jsonObject.getString("reason"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getContext(), "JSON 解析错误", Toast.LENGTH_SHORT).show();
                    }
                },
                error -> {
                    progressBar.setVisibility(View.GONE);
                    Log.e("HomeFragment", "Volley Error: " + error.toString());
                    Toast.makeText(getContext(), "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                });

        if (getContext() != null) { // 确保 Fragment 仍然附加到 Activity
            VolleySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
        }
    }
}